<?php

namespace App\Models\Voter;

use App\Models\User\WxUser;
use App\Models\WxChat;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class WxVoterPlayer extends Model
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'wx_voter_player';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // 在模型创建之前触发的操作
        });

        static::created(function ($model) {

        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($key == 'status'){
                    $originalValue = $original[$key] ?? 0;
                    if($value == 1){
                        if($originalValue == 0){
                            $voter = WxVoter::find($model->voter_id);
                            UserUtils::add_user_notice(8002, $model->user_id,'选手报名审核通过','您报名"<a href="/pagesV/voter/detail/detail?id='.$voter->id.'">'.$voter->title.'</a>"选票活动审核已通过，快去分享给小伙伴们吧',100);
                        }
                    }else{
                        if($originalValue == 1){
                            $voter = WxVoter::find($model->voter_id);
                            UserUtils::add_user_notice(8002, $model->user_id,'选手报名审核失败','您报名"<a href="/pagesV/voter/detail/detail?id='.$voter->id.'">'.$voter->title.'</a>"选票活动审核失败，经审核，您提交的资料不合法',100);
                        }
                    }
                }
            }
        });

        static::deleting(function ($user) {
            // 在软删除或真实删除前执行的逻辑
            // 例如：记录日志、发送通知等
        });

        static::deleted(function ($player) {
            // 删除他的投票
            WxVoterPlayerBallot::where('user_id', $player->user_id)->delete();
            WxChat::where('expand_type', 105)->where('expand_id', $player->id)->forceDelete();
        });
        // 其他的模型事件监听...
    }

    public function getImgUrlsAttribute($value){
        if($value && is_string($value)){
            return json_decode($value, true);
        }
        return [];
    }

    public function ower()
    {
        return $this->hasOne(WxUser::class, 'id', 'user_id');
    }

}
